package logic

import (
	"common/dao/query"
	comJwt "common/jwt"
	"common/modelrsa"
	"context"
	"errors"
	"gateway/internal/svc"
	"gateway/internal/types"
	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq) (resp *types.UserLoginResp, err error) {
	// todo: add your logic here and delete this line
	resp = &types.UserLoginResp{}
	q := query.Use(l.svcCtx.DB).SysUser
	table := q.WithContext(l.ctx)
	user, err := table.Where(q.Account.Eq(req.Username)).First()
	if err != nil {
		return resp, errors.New("账号或密码错误1")
	}
	decrypt, err := modelrsa.Decrypt(req.PassWord)
	flag := modelrsa.CheckPasswordHash(decrypt, user.Password)
	if !flag {
		return resp, errors.New("账号或密码错误2")
	}
	RegisteredClaims := jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(time.Now().AddDate(0, 0, l.svcCtx.Config.Auth.AccessExpire)),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
	}
	claims := comJwt.UserStdClaims{
		NickName:         user.NickName,
		Account:          user.Account,
		Phone:            user.Phone,
		Sex:              user.Sex,
		UUID:             user.UUID,
		Address:          user.Address,
		Shops:            user.Shops,
		Auth:             user.Auth,
		RegisteredClaims: RegisteredClaims,
	}
	token, err := comJwt.GetToken(claims, l.svcCtx.Config.Auth.AccessSecret)
	if err != nil {
		return nil, err
	}
	resp.Token = token
	return
}
